package com.smzd.framework.oauth2.api;

import java.security.Principal;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smzd.framework.config.authentications.BridgeAuthentication;
import com.smzd.framework.system.business.MeetingService;
import com.smzd.framework.system.business.UserService;
import com.smzd.framework.system.domain.Meeting;
import com.smzd.framework.system.domain.User;
import com.smzd.framework.system.domain.UserSecurity;
import com.smzd.framework.utils.ConcurrentMapUtil;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.MeetingSessionHolder;
import com.smzd.framework.utils.Privilege;
import com.smzd.utils.SessionHolder;

@Controller
public class FrameworkAPI {
    @Autowired
    @Qualifier("org.springframework.security.authenticationManager")
    protected AuthenticationManager authenticationManager;
    @Autowired
    MeetingService meetingService;
    @Autowired
    UserService userService;

    @RequestMapping(value = "/oauth2web/prepare", method = RequestMethod.POST)
    public String getBridgeKey(Principal principal) {
        Authentication oa = (Authentication) principal;
        User user = (User) oa.getPrincipal();
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();
        ConcurrentMapUtil.getUserConcurrentMap().put(uuidStr, user);
        return JsonHelper.getSuccessJsonString("key", uuidStr);
    }

    @RequestMapping(value = "/oauth2web/bridge")
    public String bridgeToBrowser(String key, String redirect_uri, HttpServletRequest request) {
        if (redirect_uri == null || redirect_uri.length() == 0) {
            redirect_uri = "/workspace";
        }
        User user = ConcurrentMapUtil.getUserConcurrentMap().remove(key);
        if (user == null) {
            return "redirect:/error";
        }
        SecurityContextHolder.getContext().setAuthentication(null);
        SessionHolder.clearObjects();
        SecurityContextHolder.clearContext();
        UserSecurity.enableUserSecurity(user);
        BridgeAuthentication token = new BridgeAuthentication(user, user.getAuthorities());
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager.authenticate(token);

        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
        SessionHolder.setObject(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());
        user = (User) authenticatedUser.getPrincipal();
        System.out.println("登录用户：" + user);
        SessionHolder.setObject(MeetingSessionHolder.KEY_LOGIN_USER, user);
        System.out.println("SessionHolder保存用户" + user);
        Meeting meeting = null;
        if (user.getType() == User.USER_TYPE_MEETING_MANAGER) {// 普通会务管理员
            meeting = meetingService.getItemById(user.getOwner().getId());
            SessionHolder.setObject(MeetingSessionHolder.KEY_MEETING, meeting);
            Privilege privilege = userService.getPrivilegeForUser(user);
            SessionHolder.setObject(MeetingSessionHolder.KEY_PRIVILEGE, privilege);
            System.out.println("SessionHolder保存权限" + privilege);
        } else if (user.getType() == User.USER_TYPE_MEETING_OWNER) {// 会务负责人
            List<Meeting> meetings = meetingService.getMeetingsByOwnerId(user.getId());

            // 就此一个，不用选会
            meeting = meetings.get(0);
            meeting.setOwner(user);
            SessionHolder.setObject(MeetingSessionHolder.KEY_MEETING, meeting);
            System.out.println("SessionHolder保存会务" + meeting);
            Privilege privilege = userService.getPrivilegeForOwner(meeting);
            SessionHolder.setObject(MeetingSessionHolder.KEY_PRIVILEGE, privilege);
            System.out.println("SessionHolder保存权限" + privilege);
        }
        return "redirect:" + redirect_uri;
    }

}
